<template>
  <div class="category-container">
    <div class="table-container">
      <avue-crud
        ref="crudRef"
        :data="data"
        :option="option"
        :page="page"
        v-model:page="page"
        @size-change="sizeChange"
        @current-change="currentChange"
        @search-change="searchChange"
        @search-reset="searchReset"
        @on-load="onLoad"
        @row-save="onSave"
        @row-update="onUpdate"
        @row-del="onDelete"
        :loading="loading"
      >
        <!-- 自定义状态列 -->
        <template #status="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '显示' : '隐藏' }}
          </el-tag>
        </template>
        
      </avue-crud>
    </div>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import { getCategoryPage, addCategory, updateCategory, deleteCategory } from '@/api/category'

// 表格配置
const option = {
  align: 'center',
  menuAlign: 'center',
  searchMenuSpan: 6,
  border: true,
  index: true,
  viewBtn: true,
  editBtn: true,
  delBtn: true,
  page: true,
  pageSizes: [10, 20, 30, 50],
  paginationAlign: 'center',
  searchShowBtn: true,
  searchResetBtn: true,
  column: [
    {
      label: '分类名称',
      prop: 'title',
      search: true,
      rules: [
        { required: true, message: '请输入分类名称', trigger: 'blur' }
      ]
    },
    {
      label: '分类ID',
      prop: 'categoryId',
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      dicData: [
        { label: '显示', value: 1 },
        { label: '隐藏', value: 0 }
      ],
      search: true,
      slot: true,
      rules: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    },
    {
      label: '创建时间',
      prop: 'createTime',
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      addDisplay: false,
      editDisplay: false
    },
    {
      label: '更新时间',
      prop: 'updateTime',
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      addDisplay: false,
      editDisplay: false
    }
  ]
}

// 数据对象
const data = ref([])
const loading = ref(false)
const page = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// 加载数据
const onLoad = async (pagination, params) => {
  try {
    loading.value = true
    const queryParams = {
      current: pagination?.currentPage || page.value.currentPage,
      size: pagination?.pageSize || page.value.pageSize,
      title: params?.title || undefined
    }
    
    // 移除undefined的属性
    Object.keys(queryParams).forEach(key => 
      queryParams[key] === undefined && delete queryParams[key]
    )
    
    const res = await getCategoryPage(queryParams)
    if (res.data.code === 200) {
      const { records, total } = res.data.data
      data.value = records
      page.value = {
        ...page.value,
        total
      }
    } else {
      ElMessage.error(res.data.msg || '获取分类列表失败')
    }
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 新增分类
const onSave = async (row, done, loading) => {
  try {
    loading(true)
    const res = await addCategory(row)
    if (res.data.code === 200) {
      ElMessage.success('添加成功')
      done()
      onLoad(page.value)
    } else {
      ElMessage.error(res.data.msg || '添加失败')
    }
  } catch (error) {
    ElMessage.error('添加失败')
  } finally {
    loading(false)
  }
}

// 更新分类
const onUpdate = async (row, index, done, loading) => {
  try {
    loading(true)
    const res = await updateCategory(row)
    if (res.data.code === 200) {
      ElMessage.success('更新成功')
      done()
      onLoad(page.value)
    } else {
      ElMessage.error(res.data.msg || '更新失败')
    }
  } catch (error) {
    ElMessage.error('更新失败')
  } finally {
    loading(false)
  }
}

// 删除分类
const onDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteCategory(row.id)
    if (res.data.code === 200) {
      ElMessage.success('删除成功')
      onLoad(page.value)
      return true
    } else {
      ElMessage.error(res.data.msg || '删除失败')
      return false
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
    return false
  }
}

// 分页大小改变
const sizeChange = (val) => {
  page.value.pageSize = val
  onLoad(page.value)
}

// 当前页改变
const currentChange = (val) => {
  page.value.currentPage = val
  onLoad(page.value)
}

// 搜索条件改变
const searchChange = (params, done) => {
  onLoad(page.value, params)
  done()
}

// 重置搜索
const searchReset = () => {
  onLoad(page.value)
}
</script>


<style scoped>
.category-container {
  background-color: var(--white-color);
  padding: var(--main-padding);
  border-radius: var(--border-radius);
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  position: relative;
}

.table-container {
  flex: 1;
  overflow: auto;
  position: relative;
}

:deep(.avue-crud__pagination) {
  position: sticky;
  bottom: 0;
  background-color: var(--white-color);
  margin-top: 16px;
  padding: 16px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 10;
}

:deep(.avue-crud__menu) {
  background-color: var(--white-color);
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}
</style> 